#include"cli_head.h"


int recvmasge(int netfd,TLVMsg *msg)
{
    bzero(msg,sizeof(TLVMsg));
    int rest=0;
    rest=recv(netfd,&msg->type,sizeof(int),MSG_WAITALL);
    if(rest==0)
    {
        return -1;
    }
    rest=recv(netfd,&msg->value_len,sizeof(int),MSG_WAITALL);
    if(rest==0)
    {
        return -1;
    }
    rest=recv(netfd,&msg->value,msg->value_len,MSG_WAITALL);
    if(rest==0)
    {
        return -1;
    }

    // msg->value[msg->value_len]='\0'; //确保字符串结束
    printf("收到消息：type=%d, value_len=%d, value=%s\n", msg->type, msg->value_len, msg->value);
    return 0;

}

int sendmasge(int netfd,int cont, int len,char *buf)
{
    TLVMsg sendmsg;
    bzero(&sendmsg,sizeof(TLVMsg));
    sendmsg.type=cont;
    sendmsg.value_len=len;
    memcpy(sendmsg.value, buf, len);
    sendmsg.value[sendmsg.value_len]='\0';

    send(netfd,&sendmsg.type,sizeof(int),MSG_NOSIGNAL);
    send(netfd,&sendmsg.value_len,sizeof(int),MSG_NOSIGNAL);
    send(netfd,&sendmsg.value,sendmsg.value_len,MSG_NOSIGNAL);
    printf("type:%d,len:%d,value:%s\n",sendmsg.type,sendmsg.value_len,sendmsg.value);
    return 0;

}


int clicent_login_in(char *user,char * passwd ,int sockfd)
{
    TLVMsg usermsg;
    bzero(&usermsg,sizeof(usermsg));
    //1.客户端发送name; 
    sendmasge(sockfd,CMD_SIGN,strlen(user),user);
    
    //2.判断是否有用户
    recvmasge(sockfd,&usermsg);
    if(strcmp("1",usermsg.value)==0)
    {
        printf("username havenot please sign in username.value=%s\n",usermsg.value);
        return 0;
    }else if(strcmp("1",usermsg.value)==1){}
    else{
        printf("server is error\n");
        return 1;
    }


    //2.接收服务端发送盐值
    char salt[33];
    recvmasge(sockfd,&usermsg);
    strcpy(salt,usermsg.value);
    //3.客户端发送密文
    char buf[65];
      //crypt_r准备工作
    struct crypt_data data;
    data.initialized = 0; //需初始化

    //对输入密码进行加密 对比
    //根据sp_pwdp中有盐值+哈希值 crypt_r 会自动截断->按盐值加密
    char *crypt_pass = crypt_r(passwd, salt, &data); 

    //snprintf(buf,sizeof(buf),"%s",*crypt(passwd,salt));

    sendmasge(sockfd,CMD_SIGN,sizeof(buf),buf);
    //revs(netfd,user->hashed_password,sizeof(user->hashed_password),MSG_WAITALL);

    //4.收-----杜------
    bzero(&usermsg,sizeof(usermsg));
    recvmasge(sockfd,&usermsg);
    printf("%s\n",usermsg.value);
    return 0;
}




int main()
{
    int sockfd =socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in cli_addr;
    cli_addr.sin_family = AF_INET;
    cli_addr.sin_port = htons(36666);
    cli_addr.sin_addr.s_addr = inet_addr("192.168.7.22");

    connect(sockfd, (struct sockaddr *)&cli_addr, sizeof(cli_addr));    

    printf("客户端连接到服务器成功，sockfd=%d\n", sockfd);

    char username[32];
    char pass[65];
    scanf("%s %s",username,pass);
    // sendmasge(sockfd,8,)
    // recvmasge(sockfd,&msg);
    //
    //clicent_login_in(username,pass,sockfd);
    return 0;


}
